import { ref, unref } from 'vue';
import { useUserStore } from '../store/modules/user';
import { useGlobSetting } from '../hooks/setting';
import { getToken } from './auth';
import { buildUUID } from './uuid';
import { getDeviceId } from './util';

const userStore = useUserStore();
let userId = unref(userStore.getUserInfo).id;

interface WebSocketOptions {
  url: string;
  token: string;
  timeoutNumber?: number;
  againTime?: number;
}

class WebSocketClass {
  private url: string;
  private data: any = null;
  private isConnect = false;
  private isInitiative = false;
  private timeoutNumber: number;
  private heartbeatTimer: number | null = null;
  private reconnectTimer: number | null = null;
  private socket: WebSocket | null = null;
  private againTime: number;

  constructor(options: WebSocketOptions) {
    // this.url = `${options.url}${options.token}`;
    this.timeoutNumber = options.timeoutNumber || 10; // Default to 10 seconds
    this.againTime = options.againTime || 5; // Default to 3 seconds
    this.initSocket();
  }

  private messageCallback: (msg: string) => void = () => {};

  // 初始化 WebSocket 连接
  private initSocket() {
    const userId = useUserStore().getUserInfo?.id;
    const domainURL = useGlobSetting().uploadUrl!;
    const domain = domainURL.replace('https://', 'wss://').replace('http://', 'ws://');
    const url = `${domain}/websocket/chat/${userId == 'e9ca23d68d884d4ebb19d07889727dae' ? 'e9ca23d68d884d4ebb19d07889727dae' : getDeviceId()}`;
    console.log('ursl = =1>', url);
    //update-begin-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
    // let token = (getToken() || '') as string;
    this.socket = new WebSocket(url);
    this.createSocket();
  }

  // 创建 WebSocket 连接
  private createSocket() {
    if (!this.socket) return;

    this.socket.onopen = () => {
      console.log('WebSocket 连接成功');
      this.isConnect = true;
      this.clearTimers();
      this.heartbeatCheck();
    };

    this.socket.onmessage = (event) => {
      this.onSocketMessageCallback(event.data);
    };

    this.socket.onclose = () => {
      console.log('WebSocket 关闭了');
      this.isConnect = false;
      this.reconnect();
    };

    this.socket.onerror = (event) => {
      console.log('WebSocket 出错了', event);
      this.isInitiative = false;
    };
  }

  // 发送消息
  public sendMsg(value: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
        return reject('WebSocket 未连接或已关闭');
      }
      this.socket.send(value);
      resolve(true);
    });
  }

  // 收到消息的回调
  private onSocketMessageCallback(msg: string) {
    this.messageCallback(msg);
  }

  public setMessageCallback(callback: (msg: string) => void) {
    this.messageCallback = callback;
  }

  // 开启心跳检测
  private heartbeatCheck() {
    console.log('开启心跳');
    this.heartbeatTimer = window.setInterval(() => {
      this.sendMsg(JSON.stringify({ type: 'heart_beat', content: 'ping' })).catch((error) => {
        console.log('发送心跳失败', error);
      });
    }, this.timeoutNumber * 1000);
  }

  // 重新连接
  private reconnect() {
    this.clearTimers();

    if (!this.isInitiative) {
      this.reconnectTimer = window.setTimeout(() => {
        console.log('尝试重新连接');
        this.initSocket();
      }, this.againTime * 1000);
    }
  }

  // 关闭 WebSocket 连接
  public closeSocket(reason = '关闭') {
    if (!this.socket) return;
    this.isInitiative = true;
    this.socket.close(1000, reason);
    this.clearTimers();
    this.isConnect = false;
    console.log('关闭 WebSocket 成功');
  }

  // 清除定时器
  private clearTimers() {
    if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
    if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
  }
}

export default WebSocketClass;
